/* 
 * File:   button.c
 * Author: Marcel
 *
 * Created on 11. September 2012, 04:32
 */


#include <p18f2620.h>
#include "timer.h"
#include "button.h"

unsigned char btn = 0, btn_old = 0, cnt = 0;
unsigned char button_debounce(void) {
    if(cnt <= 2) {
        if(timer_2ms())
            cnt++;
    }
    else {
        // Button 1
        if((PORT_BUTTON1 == 1) && (PORT_BUTTON1 == (btn_old & BUTTON1)))
            btn |= PORT_BUTTON1;
        else {
            btn &= ~BUTTON1;
            btn_old &= ~BUTTON1;
        }

        // Button 2
        if((PORT_BUTTON2 == 1) && (PORT_BUTTON2 == (btn_old & BUTTON2) >> 1))
            btn |= PORT_BUTTON2 << 1;
        else {
            btn &= ~BUTTON2;
            btn_old &= ~BUTTON2;
        }
        cnt = 0;
    }

    btn_old |= PORT_BUTTON1;
    btn_old |= PORT_BUTTON2 << 1;

    return btn;
}

unsigned char btn_ret = 0, debounce_btn_old = 0;
unsigned char button_pressed(unsigned char debounce_btn) {
    if(((debounce_btn_old & BUTTON1) == 0) && ((debounce_btn & BUTTON1) == 1)) {
        btn_ret |= BUTTON1;
    }
    else {
        btn_ret &= ~BUTTON1;
    }

    if(((debounce_btn_old & BUTTON2) == 0) && (((debounce_btn & BUTTON2) >> 1) == 1)) {
        btn_ret |= BUTTON2;
    }
    else {
        btn_ret &= ~BUTTON2;
    }


    debounce_btn_old = debounce_btn;

    return btn_ret;
}

void button_init(void) {
    DIR_BUTTON1 = 1;   // Btn 1
    DIR_BUTTON2 = 1;   // Btn 2
}